package com.xyauto.theme.utils

import android.view.View
import android.widget.ImageView
import androidx.annotation.IdRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.TransformationUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.xyauto.theme.R
import java.io.File


/**
 * 适配器相关拓展
 */
fun BaseViewHolder.setImageUrl(@IdRes id: Int, url: String) = apply {
    getViewOrNull<ImageView>(id)?.setImageUrl(url)
}

fun com.zhpan.bannerview.BaseViewHolder<*>.setImageUrl(@IdRes id: Int, url: String) = apply {
    findViewById<ImageView>(id)?.setImageUrl(url)
}

fun BaseViewHolder.setSelected(@IdRes id: Int, selected: Boolean) = apply {
    getViewOrNull<View>(id)?.isSelected = selected
}

fun ImageView.setImageUrl(url: String) {
    Glide.with(context)
        .load(url)
        .placeholder(R.drawable.default_preview)
        .transform(CenterMin())
        .dontAnimate()
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .into(this)
}


fun <T> String.toBean(clazz: Class<T>): T = Gson().fromJson(this, clazz)

fun Any.toJson(): String = Gson().toJson(this)


/**
 * 根据下载的链接，截取最后一个【/】后面的内容作为文件名，
 * 文件保存默认保存在根目录的【Download-T】文件夹下，
 * 注：未对文件名称做重名处理，如果重名会出现覆盖，请自行处理此部分逻辑
 * @param outDir 输出路径
 * @param url 下载链接
 * @return 保存的文件
 */
fun createDownloadFile(outDir: String, url: String): String {
    return getSavedFile(url, outDir).absolutePath
}

/**
 * 递归删除目录下的所有文件及子目录下所有文件
 * @param dir 将要删除的文件目录
 * @return true：删除完毕 false：递归的删除过程出现了失败
 */
fun deleteDir(dir: File): Boolean {
    if (dir.isDirectory) {
        val children = dir.list() ?: return false
        for (i in children.indices) {
            val success = deleteDir(File(dir, children[i]))
            if (!success) {
                return false
            }
        }
    }
    return dir.delete()
}

/**
 * 根据下载的链接，截取最后一个【/】后面的内容作为文件名
 * @param url 下载链接
 * @param saveCatalogue 需要保存的目录
 * @return 保存的文件
 */
private fun getSavedFile(url: String, saveCatalogue: String): File {
    val catalogue = File(saveCatalogue)
    if (!catalogue.exists()) {
        catalogue.mkdirs()
    }
    val lastIndex = url.lastIndexOf("/").let {
        if (it <= -1) {
            0
        } else {
            it
        }
    }
    val fileName = url.substring(lastIndex, url.length).let {
        it.ifBlank {
            System.currentTimeMillis().toString()
        }
    }
    val savePath = catalogue.absolutePath + File.separator + fileName
    val saveFile = File(savePath)
    if (saveFile.exists()) {
        saveFile.createNewFile()
    }
    return saveFile
}


fun getFileNameByUrl(url: String): String {
    return url.substring(url.lastIndexOf("/").let { if (it <= -1) 0 else it + 1 }, url.length).let {
        it.ifBlank {
            System.currentTimeMillis().toString()
        }
    }
}